<template>
	<div class="cmt-container">
		<h3>发表评论</h3>
		<hr>
		<textarea placeholder="请输入要bb的内容(不得少于6字,高于120字)" v-model="msg" :maxlength="maxcount" :minlength="minCount"></textarea>
		<mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
		<div class="cmt-body" v-for="(itme,i) in newsCmt" :key="itme.add_time">
			<p class="cmt-title">第{{ i + 1 }}楼 &nbsp;&nbsp; {{ itme.user_name }} &nbsp;&nbsp; 发表时间：{{ itme.add_time | dataFormat('YYYY-MM-DD') }}</p>
			<div class="cmt-content">{{ itme.content == "undefined" ? "此用户什么都没有说！" : itme.content}}</div>
		</div>
		<mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
	</div>
</template>

<script>
	import { Toast } from 'mint-ui';
	export default {
		data(){
			return {
				idx: 1,
				newsCmt: [],
				msg: "",
				maxcount: 120,
				minCount: 6
			}
		},
		methods: {
			getComments(){
				this.$http.get(`api/getcomments/${this.id}?pageindex=${this.idx}`).then(res=>{
					if (res.body.status == 0){
						//concat() 方法用于连接两个或多个数组。该方法不会改变现有的数组，而仅仅会返回被连接数组的一个副本。
						this.newsCmt = this.newsCmt.concat(res.body.message);
					} else {
						Toast('获取评论数据失败！');
					}
				})
			},
			getMore(){
				this.idx++;
				this.getComments();
			},
			postComment(){
				if (this.msg.trim().length == 0 ) {
					Toast('你发表的评论内容为空！');
				} else {
					this.$http.post(`api/postcomment/${this.id}`,{content: this.msg.trim()}).then(res=>{
						if (res.body.status == 0) {
							let newComment = {
								user_name: "匿名用户",
								add_time: Date.now(),
								content: this.msg.trim()
							}
							this.newsCmt.unshift(newComment);
							this.msg = "";
						} else {
							Toast('服务器繁忙！');
						}
					})
				}
			}
		},
		created(){
			this.getComments();
			console.log(this.newsCmt)
		},
		props: ["id"]
	}
</script>

<style lang="scss" scoped="scoped">
	.cmt-container{
		padding: 0px 5px;
		h3{
			font-size: 18px;
		}
		textarea{
			font-size: 14px;
			height: 85px;
			margin-bottom: 3px;
		}
		.cmt-body{
			margin-top: 5px;
			font-size: 12px;
			.cmt-title{
				background: #ccc;
				height: 30px;
				color: black;
				line-height: 30px;
				margin-bottom: 0px;
			}
			.cmt-content{
				height: 40px;
				line-height: 40px;
			}
		}
	}
</style>
